"""
Copyright 2009, Jay Shurtz.

This is free software; you can redistribute it and/or modify it
under the terms of the GNU Lesser General Public License as
published by the Free Software Foundation; either version 2.1 of
the License, or (at your option) any later version.

This software is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
Lesser General Public License for more details.

You should have received a copy of the GNU Lesser General Public
License along with this software; if not, write to the Free
Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA
02110-1301 USA, or see the FSF site: http://www.fsf.org.

Module for making object logging easy to implement.
"""  

HEAD_URL = "$HeadURL: https://taggle.jira.com/svn/TOOLS/trunk/python_modules/easy_logger.py $"
REVISION = "$Revision: 2038 $"
AUTHOR = "$Author: jayshurtz $"
DATE = "$Date: 2010-08-11 13:57:07 +1000 (Wed, 11 Aug 2010) $"
ID = "$Id: easy_logger.py 2038 2010-08-11 03:57:07Z jayshurtz $"
version = " ".join(ID.split()[2:4])


import logging


# Define logging levels.
loggingLevels = {'debug': logging.DEBUG, 'info': logging.INFO,
    'warning': logging.WARNING, 'error': logging.ERROR, 'critical': logging.CRITICAL}


def setLogLevel(level, logOrHandler, loggingLevels=loggingLevels):
    """ Set logger or log handler level.
        'level' is a string in loggingLevels.keys().
    """
    loggingLevel = loggingLevels[level]
    logOrHandler.setLevel(loggingLevel)


try:
    NullHandler = logging.NullHandler
except AttributeError, e:
    class NullHandler(logging.Handler):
        """ Null log handler class for older version of Python.
        """
        def emit(self, record):
            pass


class EasyLogger(object):
    """ Super class for making object logging easy to implement.
        Generally each object should log messages to its own logger,
        and each script should define the log handlers which receive the messages.
    """
    def __init__(self, loggerName=None, logHandlers=[]):    # TODO - pass in log file directory and format/dateformat ?
        """ This class always has a logger and a default log handler,
            Logging to additional handlers is supported via the "logHandlers" parameter.
            'loggerName' is a unique string that names the logger.
            'logHandlers' is a list of additional log handlers (such as logging.FileHandler instances). 
        """
        if loggerName is None:
            loggerName = self.__class__.__name__    # Set by inheriting class.
        self.logger = logging.getLogger(loggerName)
        self.logger.setLevel(logging.DEBUG) # Always log debug messages.
        defaultHandler = self.__getDefaultLogHandler()
        self.logger.addHandler(defaultHandler)  # Always log here, additional handlers may also be passed in.
        self.addLogHandlers(logHandlers)    # Add any additional log handlers.

    def __getDefaultLogHandler(self, logFormat="%(asctime)s  %(name)s  %(levelname)s  %(message)r", dateFormat=None):
        """ Create the default log handler for this object.
        """
        #defaultHandler = logging.FileHandler(self.logger.name + '.log', 'w')
        #defaultHandler.setLevel(logging.DEBUG) # Always log debug messages.
        #defaultHandler.setFormatter(logging.Formatter(logFormat, dateFormat))
        defaultHandler = NullHandler()
        return defaultHandler

    def addLogHandlers(self, logHandlers=[]):
        """ Add log handlers to self.logger.
        """
        for handler in logHandlers:
            if handler not in self.logger.handlers:
                self.logger.addHandler(handler)


# Main for testing.
if __name__ == "__main__":

    class ELC(EasyLogger):
        pass

    # Objects should log, *not* scripts (unless in __main__).
    consoleHandler = logging.StreamHandler()
    consoleHandler.setLevel(logging.DEBUG)
    #consoleHandler.setFormatter(logging.Formatter("%(asctime)s  %(name)s  %(levelname)s  %(message)r"))
    elc = ELC('ELC_loggerName', [consoleHandler])
    elc.logger.debug("debug message.")

